<?php

/**
 * 曼伦 SDK
 * @author chenyun
 * 
 */

namespace App\Service\VendorClient\Shopmanlun;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use function GuzzleHttp\json_encode;
use App\Model\PssModel\ServiceConfig;
class ShopmanlunApiClient
{
    private $account  = 'shopmanlun';
    protected $config;
    protected $RouteMap = [
        'createOrder'   => 'Order.Info.Create',
        'cancelOrder'   => 'Order.Refund.Create',
    ];
 
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //商品总金额
        $goodsTotalMoney = '0.00';
        //商品下单组
        $items = [];
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];

            $items[]= [
                'title'        => $item['goods_name'],//商品标题。
                'price'        => (int)bcmul($price,'100'),//销售价格。
                'sku_code'     => $item['supplier_skucode'],//商品SKU代码。
                'quantity'     => $quantity,//购买数量。单个SKU购买的件数
            ];
            $goodsMoneyRow = bcmul((string)$price,(string)$quantity,2);
            $goodsTotalMoney = bcadd($goodsTotalMoney, $goodsMoneyRow, 2);
        }
        //实际下单金额
        $real_total_money = $orderInfo['real_total_money'];
        //运费
        $deliver_money=$orderInfo["deliver_money"];
        // 订单交易金额，单位: 分。交易金额 + 运费 - 优惠金额 = 支付金额
        $orderMoney = bcadd($goodsTotalMoney, (string)$deliver_money, 2);
        $discountMoney = bcsub($orderMoney, (string)$real_total_money, 2);
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $apply_extends['paySerial'];
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        }
        $payment=[
            "pay_order_no"      => $orderInfo['supplier_dsn'],
            "declare_order_no"  => $pay_sn,
            "pay_time"          => $pay_time,
            "pay_amount"        => (int)(bcmul($real_total_money,'100')),
            "pay_channel"       => (int)$pay_value,
        ];
        $clearance=[
            "clearance_name"    => $orderInfo["buyer_realname"],
            "clearance_no"      => $orderInfo["buyer_idcard"],
        ];
        $receiver=[
            "receiver_name"     => $orderInfo['receive_name'],
            "receiver_mobile"   => $orderInfo['recveive_phone'],
            "receiver_tel"      => $orderInfo['recveive_phone'],
            "zipcode"           => "",
            "receiver_province" => $orderInfo['province'],
            "receiver_city"     => $orderInfo['city'],
            "receiver_district" => $orderInfo['district'],
            "receiver_address"  => $orderInfo['receive_address'],
        ];
        //创建订单数据
        $data = [
            "trade_no"          => $orderInfo['supplier_dsn'],
            "total_amount"      => (int)(bcmul($goodsTotalMoney,'100')),
            "post_fee"          => (int)(bcmul($deliver_money,'100')),
            "discount_fee"      => $discountMoney > 0 ? (int)(bcmul($discountMoney, '100')) : 0,
            "modification_date" => $order_time,
            "creation_date"     => $order_time,
            "custom"            => 2,
            "buyer_note"        => $orderInfo["order_remark"] ?? '',
            "mobile"            => $orderInfo["buyer_phone"],
            "payment"           => $payment,
            "clearance"         => $clearance,
            "receiver"          => $receiver,
            "items"             => $items
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        if( empty($params['supplierOrder'])) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder ");
        }
        
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $data = [
            'order_no'      => $orderInfo['supplier_dsn'],
            'refund_all'    => true,
        ];
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      =>$data,
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 加签
     * @param array $param
     */
    protected function getSign ($param)
    {
        //md5(method + appid + timestamp + data + appsecret),得到32位签名值，请求时签名不区分大小写
        $string = $param["method"].$param["appid"].$param["timestamp"].$param["data"].$this->config["appsecret"];
        $string = md5($string);
        return $string;
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if(empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param['method'];
        $url = $this->config['baseurl'];
        $timestamp=time();
        $data=[
            "method"    => $this->RouteMap[$method],
            "appid"     => $this->config["appid"],
            "timestamp" => $timestamp,
            "data"      => json_encode($param["data"],JSON_UNESCAPED_UNICODE),
        ];
        $data["sign"]=$this->getSign($data);
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'json',
                'header'    =>[
                    "Content-Type: application/x-www-form-urlencoded:charset=utf-8"
                    ],
        
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = @json_decode($res,true);
        if(isset($resHttp['success']) && $resHttp['success'] == true ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['message']) ? $resHttp['message'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}